<div class="row">
    <div class="col-md-12">
        <!-- 搜索筛选区域 -->
        <div class="card">
            <div class="card-body">
                <form method="GET" action="{{ route('dcat.admin.admin.pickup.applications.index') }}">
                    <div class="row mb-3">
                        <!-- 第一行筛选项 -->
                        <div class="col-md-2">
                            <label for="applicant_id" class="form-label">申请ID</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="applicant_id" name="applicant_id" 
                                       value="{{ $request->applicant_id ?? '' }}" placeholder="请输入申请ID">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <label for="member_info" class="form-label">门店名称/联系人/手机号</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="member_info" name="member_info" 
                                       value="{{ $request->member_info ?? '' }}" placeholder="请输入门店名称、联系人或手机号">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <label for="status" class="form-label">申请状态</label>
                            <select class="form-control" id="status" name="status">
                                <option value="">全部状态</option>
                                <option value="pending" {{ ($request->status ?? '') == 'pending' ? 'selected' : '' }}>待审核</option>
                                <option value="approved" {{ ($request->status ?? '') == 'approved' ? 'selected' : '' }}>审核通过</option>
                                <option value="rejected" {{ ($request->status ?? '') == 'rejected' ? 'selected' : '' }}>审核不通过</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label for="search_btn" class="form-label">&nbsp;</label>
                            <button type="submit" class="btn btn-primary btn-block">
                                <i class="fa fa-search"></i> 查询
                            </button>
                        </div>
                        <div class="col-md-2">
                            <label for="reset_btn" class="form-label">&nbsp;</label>
                            <a href="{{ route('dcat.admin.admin.pickup.applications.index') }}" class="btn btn-secondary btn-block">
                                <i class="fa fa-refresh"></i> 重置
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 申请列表 -->
        <div class="card mt-3">
            <div class="card-body p-0">

                <!-- 数据表格 -->
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th style="width: 100px;">申请ID</th>
                                <th style="width: 200px;">门店名称</th>
                                <th style="width: 120px;">申请人信息</th>
                                <th style="width: 120px;">联系电话</th>
                                <th style="width: 100px;">申请状态</th>
                                <th style="width: 120px;">提交时间</th>
                                <th style="width: 240px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($applications as $app)
                            <tr>
                                <td><strong>#{{ $app['id'] }}</strong></td>
                                <td>{{ $app['pickup_name'] }}</td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar avatar-sm rounded-circle mr-2">
                                            <img src="{{ $app['applicant']['avatar'] }}" alt="{{ $app['applicant']['name'] }}" class="rounded-circle" style="width: 32px; height: 32px;">
                                        </div>
                                        <div>
                                            <div><strong>{{ $app['applicant']['name'] }}</strong></div>
                                            <small class="text-muted">门店ID: {{ $app['applicant']['id'] }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>{{ $app['phone'] }}</td>
                                <td>
                                    <span class="badge {{ $app['status_class'] }}">{{ $app['status'] }}</span>
                                </td>
                                <td>
                                    <small class="text-muted">{{ $app['submitted_at'] }}</small>
                                </td>
                                <td>
                                    @if($app['status'] == '待审核')
                                        <button class="btn btn-sm btn-success mr-1" onclick="approveApplication({{ $app['id'] }})">
                                            <i class="fa fa-check"></i> 通过
                                        </button>
                                        <button class="btn btn-sm btn-danger mr-1" onclick="rejectApplication({{ $app['id'] }})">
                                            <i class="fa fa-times"></i> 拒绝
                                        </button>
                                    @else
                                        <span class="text-muted">已审核</span>
                                        @if($app['reason'])
                                            <i class="fa fa-info-circle text-info ml-1" title="{{ $app['reason'] }}" data-toggle="tooltip"></i>
                                        @endif
                                    @endif
                                    <a href="#" class="text-info ml-1" onclick="showApplicationDetail({{ $app['id'] }})">
                                        <i class="fa fa-eye"></i> 详情
                                    </a>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="7" class="text-center py-4">
                                    <i class="fa fa-inbox fa-2x text-muted mb-2"></i>
                                    <p class="text-muted">暂无申请记录</p>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                
                <!-- 底部统计和分页 -->
                <div class="d-flex justify-content-between align-items-center p-3 bg-light">
                    <div class="text-muted">
                        共 {{ $pagination->total() }} 条记录，当前第 {{ $pagination->currentPage() }} 页，共 {{ $pagination->lastPage() }} 页
                    </div>
                    <nav aria-label="申请列表分页">
                        {{ $pagination->appends(request()->query())->links() }}
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 拒绝原因弹窗 -->
<div class="modal fade" id="rejectModal" tabindex="-1" role="dialog" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rejectModalLabel">
                    <i class="fa fa-times-circle text-danger"></i> 拒绝申请
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="rejectForm">
                    <div class="form-group">
                        <label for="rejectReason">拒绝原因 <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="rejectReason" rows="4" placeholder="请输入拒绝原因..." required></textarea>
                        <small class="form-text text-muted">请详细说明拒绝原因，以便申请人了解并改进。</small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmReject()">确认拒绝</button>
            </div>
        </div>
    </div>
</div>

<!-- 申请详情弹窗 -->
<div class="modal fade" id="detailModal" tabindex="-1" role="dialog" aria-labelledby="detailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailModalLabel">
                    <i class="fa fa-info-circle"></i> 申请详情
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body p-0" id="detailContent">
                <div class="text-center py-5">
                    <i class="fa fa-spinner fa-spin fa-2x text-muted"></i>
                    <p class="text-muted mt-2">加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 14px;
}

.form-label {
    font-weight: 500;
    margin-bottom: 5px;
    color: #495057;
}

.table th {
    border-top: none;
    font-weight: 600;
    color: #495057;
    background-color: #f8f9fa !important;
}

.table td {
    vertical-align: middle;
    padding: 12px 8px;
}

.badge {
    font-size: 11px;
    padding: 4px 8px;
}

.text-primary:hover,
.text-info:hover,
.text-secondary:hover {
    text-decoration: underline;
}

.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}

/* 弹窗优化 */
.modal-dialog-scrollable {
    max-height: calc(100vh - 60px);
}

.modal-dialog-scrollable .modal-content {
    max-height: calc(100vh - 60px);
}

.modal-dialog-scrollable .modal-body {
    overflow-y: auto;
    max-height: calc(100vh - 180px);
}

@media (max-height: 600px) {
    .modal-dialog-scrollable {
        max-height: calc(100vh - 20px);
    }
    
    .modal-dialog-scrollable .modal-content {
        max-height: calc(100vh - 20px);
    }
    
    .modal-dialog-scrollable .modal-body {
        max-height: calc(100vh - 140px);
    }
}

/* 确保弹窗在屏幕中央且不超出边界 */
.modal {
    padding: 15px;
}

.modal-dialog {
    margin: 15px auto;
}
</style>

<script>
let currentApplicationId = null;

// 审核通过
function approveApplication(id) {
    Dcat.confirm('确认审核', '确定要通过这个申请吗？', function() {
        $.ajax({
            url: `/admin/pickup-applications/${id}/approve`,
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.status === 'success') {
                    Dcat.success('审核通过成功！');
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    Dcat.error('操作失败：' + response.message);
                }
            },
            error: function(xhr) {
                let message = '操作失败，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    message = xhr.responseJSON.message;
                }
                Dcat.error(message);
            }
        });
    });
}

// 拒绝申请
function rejectApplication(id) {
    currentApplicationId = id;
    $('#rejectReason').val('');
    $('#rejectModal').modal('show');
}

// 确认拒绝
function confirmReject() {
    const reason = $('#rejectReason').val().trim();
    
    if (!reason) {
        Dcat.warning('请输入拒绝原因');
        return;
    }

    $.ajax({
        url: `/admin/pickup-applications/${currentApplicationId}/reject`,
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            reason: reason
        },
        success: function(response) {
            if (response.status === 'success') {
                $('#rejectModal').modal('hide');
                Dcat.success('审核拒绝成功！');
                setTimeout(function() {
                    location.reload();
                }, 1500);
            } else {
                Dcat.error('操作失败：' + response.message);
            }
        },
        error: function(xhr) {
            let message = '操作失败，请稍后重试';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            }
            Dcat.error(message);
        }
    });
}

// 显示申请详情
function showApplicationDetail(id) {
    // 显示弹窗
    $('#detailModal').modal('show');
    
    // 重置内容为加载状态
    $('#detailContent').html(`
        <div class="text-center py-5">
            <i class="fa fa-spinner fa-spin fa-2x text-muted"></i>
            <p class="text-muted mt-2">加载中...</p>
        </div>
    `);
    
    // 发送Ajax请求获取详情数据
    $.ajax({
        url: `/admin/pickup-applications/${id}`,
        type: 'GET',
        success: function(response) {
            $('#detailContent').html(response);
        },
        error: function(xhr, status, error) {
            let errorMessage = '加载失败，请稍后重试';
            if (xhr.status === 404) {
                errorMessage = '申请记录不存在';
            } else if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMessage = xhr.responseJSON.message;
            }
            
            $('#detailContent').html(`
                <div class="text-center py-5">
                    <i class="fa fa-exclamation-triangle fa-2x text-danger"></i>
                    <p class="text-danger mt-2">${errorMessage}</p>
                    <button class="btn btn-secondary" onclick="showApplicationDetail(${id})">重新加载</button>
                </div>
            `);
        }
    });
}

// 页面加载完成后初始化
$(document).ready(function() {
    // 初始化工具提示
    $('[data-toggle="tooltip"]').tooltip();
    
    // 添加CSRF token到所有AJAX请求
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
});
</script>